package com.qf.dao;

import com.qf.pojo.Cart;
import com.qf.utils.ApacheUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.dao
 * @Description:
 * @Date 2022/5/25 19:38
 */
public class CartDaoImpl implements CartDao {
    private QueryRunner qr = new QueryRunner(ApacheUtil.getDataSource());
    @Override
    public Cart findCartByUidAndPid(Integer uid, Integer pid) {
        String sql = "select * from tb_cart where uid = ? and pid = ?";
        Cart cart = null;
        try {
            cart = qr.query(sql, new BeanHandler<Cart>(Cart.class), uid, pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return cart;
    }

    @Override
    public void updateCart(Cart cart) {
        String sql = "update tb_cart set num=? , money=? where cid=?";
        try {
            qr.update(sql,cart.getNum(),cart.getMoney(),cart.getCid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertCart(Cart cart) {
        String sql = "insert into tb_cart (uid, pid, num, money) value(?,?,?,?)";
        try {
            qr.update(sql,cart.getUid(),cart.getPid(),cart.getNum(),cart.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Cart> findCartListByUid(Integer uid) {
        String sql = "select * from tb_cart where uid=?";
        List<Cart> list = null;
        try {
            list = qr.query(sql, new BeanListHandler<Cart>(Cart.class), uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Cart findById(Integer cid) {
        String sql = "select * from tb_cart where cid = ?";
        Cart cart = null;
        try {
            cart = qr.query(sql, new BeanHandler<Cart>(Cart.class), cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return cart;
    }

    @Override
    public void deleteById(Integer cid) {
        String sql = "delete from tb_cart where cid =?";
        try {
            qr.update(sql,cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void clearCart(Integer uid) {
        String sql = "delete from tb_cart where uid =?";
        try {
            qr.update(sql,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
